﻿"""Web admin routes."""

from datetime import datetime
import logging
import os

from flask import Blueprint, jsonify, render_template, request

from config import get_config
from config.api_config import API_CONFIG
from app.services.production_service import ProductionService
from app.services.inventory_service import InventoryService
from app.services.inspection_service import InspectionService


logger = logging.getLogger(__name__)
web_bp = Blueprint("web", __name__)


@web_bp.route("/")
def index() -> str:
    """Render admin index."""

    return render_template("admin.html")


@web_bp.route("/admin")
def admin() -> str:
    """Compatibility route for legacy URL."""

    return render_template("admin.html")


@web_bp.route("/api/config", methods=["GET"])
def get_api_config():
    """Return API configuration list."""

    try:
        api_items = []
        for module_key, module in API_CONFIG.items():
            label = module.get("label", module_key)
            for endpoint_name, endpoint in module.get("endpoints", {}).items():
                api_items.append(
                    {
                        "module": module_key,
                        "module_label": label,
                        "name": endpoint_name,
                        "path": endpoint.get("path"),
                        "method": endpoint.get("method", "GET"),
                        "description": endpoint.get("description", ""),
                        "auth_required": endpoint.get("auth_required", False),
                    }
                )

        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": api_items,
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to fetch API config: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500


@web_bp.route("/api/system/config", methods=["GET"])
def get_system_config():
    """Return current runtime config."""

    try:
        config = get_config()
        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": {
                "app_key": config.APP_KEY,
                "app_secret": config.APP_SECRET,
                "app_name": config.APP_NAME,
                "tenant_id": config.TENANT_ID,
                "port": config.PORT,
                "host": config.HOST,
                "token_expire_seconds": config.TOKEN_EXPIRE_SECONDS,
                "system_name": config.SYSTEM_NAME,
                "system_version": config.SYSTEM_VERSION,
                "system_environment": config.SYSTEM_ENVIRONMENT,
            },
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to load system config: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500


@web_bp.route("/api/system/config", methods=["POST"])
def save_system_config():
    """Persist runtime configuration."""

    try:
        config = get_config()
        payload = request.get_json(force=True) or {}

        logger.info("Received config update: %s", payload)

        if "app_key" in payload:
            config.APP_KEY = payload["app_key"]
        if "app_secret" in payload:
            config.APP_SECRET = payload["app_secret"]
        if "app_name" in payload:
            config.APP_NAME = payload["app_name"]
        if "tenant_id" in payload:
            config.TENANT_ID = payload["tenant_id"]
        if "token_expire_seconds" in payload:
            config.TOKEN_EXPIRE_SECONDS = int(payload["token_expire_seconds"])
        if "system_environment" in payload:
            config.SYSTEM_ENVIRONMENT = payload["system_environment"]

        from app.services import auth_service

        auth_service.APP_CREDENTIALS = auth_service._load_app_credentials()  # noqa: SLF001
        logger.info("Auth credentials reloaded: %s", list(auth_service.APP_CREDENTIALS.keys()))

        return jsonify({
            "code": "200",
            "message": "配置已保存，已立即生效",
            "data": {
                "app_key": config.APP_KEY,
                "updated_at": datetime.now().isoformat(),
            },
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to save system config: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"保存失败: {exc}",
        }), 500


@web_bp.route("/api/logs", methods=["GET"])
def get_logs():
    """Return latest log content."""

    try:
        project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
        log_file = os.path.join(project_root, "logs", "erp_mock.log")
        lines = max(int(request.args.get("lines", 100)), 1)

        if not os.path.exists(log_file):
            return jsonify({
                "code": "200",
                "message": "获取成功",
                "data": {
                    "logs": ["日志文件不存在"],
                    "total": 1,
                },
            })

        with open(log_file, "r", encoding="utf-8") as handle:
            content = handle.readlines()

        latest = content[-lines:] if len(content) > lines else content
        logs = [line.rstrip("\n") for line in latest if line.strip()]

        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": {
                "logs": logs,
                "total": len(logs),
            },
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to read logs: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500


@web_bp.route("/api/status", methods=["GET"])
def get_server_status():
    """Provide basic server status."""

    try:
        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": {
                "status": "running",
                "uptime": "服务已运行 1 小时 30 分",
                "memory_usage": "45 MB",
                "cpu_usage": "15%",
            },
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to obtain status: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500


@web_bp.route("/api/dashboard/orders", methods=["GET"])
def dashboard_orders():
    """Provide simplified production orders for UI."""

    try:
        page = int(request.args.get("pageIndex", request.args.get("page", 1)))
        page_size = int(request.args.get("pageSize", request.args.get("page_size", 12)))

        result = ProductionService.get_order_list(
            page_index=page,
            page_size=page_size,
            is_show_process=1,
            is_show_material=True,
            is_show_by_product=True,
            is_show_activity=True,
        )

        items = []
        for record in result.get("recordList", []):
            items.append(
                {
                    "id": record.get("code"),
                    "code": record.get("code"),
                    "product": record.get("productName"),
                    "specification": record.get("specification"),
                    "planned": record.get("planQuantity", 0),
                    "finished": record.get("finishQuantity", 0),
                    "status_name": record.get("statusName", "生产中"),
                    "plan_date": record.get("planCompleteDate"),
                }
            )

        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": {
                "items": items,
                "raw": result,
            },
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to fetch dashboard orders: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500


@web_bp.route("/api/dashboard/inventory", methods=["GET"])
def dashboard_inventory():
    """Provide inventory summary for UI (uses generated demo data if available)."""

    try:
        import json
        # Try demo file first
        project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
        demo_path = os.path.join(project_root, "data", "inventory_records_50.json")
        records = None
        if os.path.exists(demo_path):
            with open(demo_path, "r", encoding="utf-8") as fh:
                records = json.load(fh)
        else:
            result = InventoryService.query_inventory(None, None, page=1, page_size=12)
            records = (
                result.get("items")
                or result.get("records")
                or result.get("recordList", [])
            )

        items = []
        for rec in (records or [])[:12]:
            items.append(
                {
                    "id": rec.get("material_code") or rec.get("product_code") or rec.get("productsku_code"),
                    "materialCode": rec.get("material_code") or rec.get("product_code"),
                    "materialName": rec.get("material_name") or rec.get("product_name"),
                    "specification": rec.get("specification") or rec.get("spec") or rec.get("productsku_name"),
                    "warehouse": rec.get("warehouse_name") or rec.get("warehouse"),
                    "quantity": rec.get("current_stock") or rec.get("currentqty") or rec.get("quantity", 0),
                    "unit": rec.get("unit") or rec.get("unit_name", ""),
                }
            )

        return jsonify(
            {
                "code": "200",
                "message": "获取成功",
                "data": {"items": items, "raw": {"records": records}},
            }
        )
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to fetch dashboard inventory: %s", exc, exc_info=True)
        return jsonify({"code": "500", "message": f"获取失败: {exc}"}), 500
@web_bp.route("/api/dashboard/reports", methods=["GET"])
def dashboard_reports():
    """Provide completion report summary for UI."""

    try:
        result = ProductionService.get_completion_reports_list(page=1, page_size=8, filters={})
        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": result,
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to fetch dashboard reports: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500


@web_bp.route("/api/dashboard/transactions", methods=["GET"])
def dashboard_transactions():
    """Provide inventory transactions for UI."""

    try:
        result = InventoryService.query_inventory_transactions({"page": 1, "page_size": 12})
        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": result,
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to fetch dashboard transactions: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500


@web_bp.route("/api/dashboard/inspections", methods=["GET"])
def dashboard_inspections():
    """Provide inspection overview for UI."""

    try:
        result = InspectionService.query_inspection_list({"pageIndex": 1, "pageSize": 10})
        return jsonify({
            "code": "200",
            "message": "获取成功",
            "data": result,
        })
    except Exception as exc:  # noqa: BLE001
        logger.error("Failed to fetch dashboard inspections: %s", exc, exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"获取失败: {exc}",
        }), 500
